<?php
/**
 * User: ppjun378
 * Data: 2018/11/15
 * Time: 14:30
 */

namespace App\Service;

use App\Model\Assets;
use App\Model\Receives;

class ReceivesService
{
    /**
     * 获取列表数据
     * @param $request
     * @return mixed
     * @author ppjun378 <ppjun378@foxmail.com>
     */
    public static function dataList($request)
    {
        $keyword = $request->input('keyword', '');
        $size = $request->input('limit', 10); // 每页显示的数据条数
        $status = (int) $request->input('status', '');
        $order_method = (int) $request->input('order_method', 0);
        $fields = ['receives.id', 'borrow_number', 'borrow_user', 'borrow_date', 'address_type_id', 'address', 'select_assets', 'borrow_operator', 'receives.status', 'personnels.personnel_name as borrow_user', 'companys.company_name', 'signature_images'];

        $coding = $request->input('coding', '');
        $asset_name = $request->input('asset_name', '');
        $sn = $request->input('sn', '');

        if (empty($coding) && empty($asset_name) && empty($sn)) {
            $new_select_assets = 1;
            $asset_count = 0;
            $asset_id_data = '';
        } else {
            $asset_id_data = Assets::select('id')
                ->when($coding, function ($query) use ($coding) {
                    return $query->where('coding', 'like', '%' . $coding . '%');
                })
                ->when($asset_name, function ($query) use ($asset_name) {
                    return $query->where('name', 'like', '%' . $asset_name . '%');
                })
                ->when($sn, function ($query) use ($sn) {
                    return $query->where('sn', 'like', '%' . $sn . '%');
                })
                ->get()
                ->toArray();

            // array_map();将函数作用到数组中的每个值上，每个值都乘以本身，并返回带有新值的数组：
            // array_shift删除数组中的第一个元素，并返回被删除元素的值：

            $new_select_assets = implode(',', array_map('array_shift', $asset_id_data));
            $asset_count = 1;

        }
        // $new_select_assets = array_map('array_shift', $data);

        if (empty($new_select_assets)) {
            $list['code'] = 0;
            $list['msg'] = '暂无数据';
        } else {
            $borrow_number = $request->input('borrow_number', '');
            $borrow_operator = $request->input('borrow_operator', '');
            $data = Receives::select($fields)
                ->join('personnels', 'personnels.id', '=', 'receives.borrow_user')
                ->join('companys', 'companys.id', '=', 'receives.use_company_id')
                ->when($status, function ($query) use ($status) {
                    return $query->where('borrows.status', $status); //借用单状态 0：空状态 1:待签字 2：已签字 -2:打回
                })
                ->when($borrow_number, function ($query) use ($borrow_number) {
                    $query->orWhere('borrow_number', 'like', '%' . $borrow_number . '%');
                })
                ->when($borrow_operator, function ($query) use ($borrow_operator) {
                    $query->orWhere('borrow_operator', $borrow_operator);

                })
                ->where(function ($query) use ($keyword) {
                    $query->orWhere('borrow_number', 'like', '%' . $keyword . '%');
                    // ->orWhere('coding', 'like', '%' . $keyword . '%');
                    // if ($keyword) {
                    //     $query->whereRaw('concat(`borrow_number`) like ' . '\'%' . $keyword . '%\'');
                    // }

                })
                ->when($new_select_assets, function ($query) use ($asset_id_data, $asset_count) {
                    if (!empty($asset_id_data) && !empty($asset_count)) {
                        foreach ($asset_id_data as $key => $val) {
                            $query->orWhere('select_assets', 'like', '%-' . $val['id'] . '-%');
                        }
                    }
                })
                ->when($order_method, function ($query) use ($order_method) {
                    if ($order_method == 1) {
                        return $query->orderBy('receives.borrow_date', 'asc');
                    } else {
                        return $query->orderBy('receives.borrow_date', 'desc');
                    }
                })
                ->orderBy('receives.id', 'desc')
                ->paginate($size);

            $list['code'] = 0;
            $list['msg'] = "查询成功";
            $list['count'] = count($data);
            $data = $data->toArray();

            //计算资产个数
            foreach ($data['data'] as $k => $v) {
                $data['data'][$k]['assets_count'] = count(explode(',', $v['select_assets']));
                unset($data['data'][$k]['select_assets']);
            }

            $list['data'] = $data['data'];
        }
        return $list;
    }

    /**
     * 详情
     * @param $id
     * @return mixed
     * @author ppjun378 <ppjun378@foxmail.com>
     */
    public static function getDetail($request)
    {
        $id = $request->input('id', '');
        $field = ['borrow_number', 'borrow_user', 'borrow_date', 'address_type_id', 'address', 'select_assets', 'borrow_operator', 'receives.status', 'borrow_user', 'personnels.personnel_name as borrow_user_name', 'companys.company_name', 'use_department_id', 'expect_revert_date', 'borrow_operator', 'comment'];
        $data = Receives::select($field)
            ->join('personnels', 'personnels.id', '=', 'receives.borrow_user')
            ->join('companys', 'companys.id', '=', 'receives.use_company_id')
            ->where('receives.id', $id)
            ->first();

        $data = $data->toArray();

        $field = ['assets.id', 'name', 'coding', 'specification', 'sn', 'image as asset_image', 'location', 'companys.company_name as use_the_company_name'];
        $data['select_assets'] = Assets::select($field)
            ->join('companys', 'companys.id', '=', 'assets.company_id')
            ->whereIn('assets.id', explode(',', rtrim(str_replace('-', '', $data['select_assets']), ',')))
            ->get();

        $list['code'] = 0;
        $list['msg'] = "查询成功";
        $list['data'] = $data;

        return $list;
    }

    /**
     * 添加/更新
     * @param $request
     * @return mixed
     * @author ppjun378 <ppjun378@foxmail.com>
     */
    public static function store($request)
    {
        $data = $request->all();
        $id = $request->input('id', '');
        $map = [];
        $fields = ['borrow_number', 'borrow_user', 'borrow_date', 'use_company_id', 'use_department_id', 'address_type_id', 'address', 'expect_revert_date', 'borrow_operator', 'comment', 'select_assets', 'status', 'signature_images'];
        foreach ($data as $k => $v) {
            if ($v === null) {$v = '';}
            if (in_array($k, $fields) && !empty($v)) {
                $map[$k] = $v;
            }
            if ($k == 'select_assets') {
                $select_asset_id = explode(',', $v);
                $new_select_asset_id = array();
                foreach ($select_asset_id as $kay => $val) {
                    if ($val > 0) {
                        $new_select_asset_id[] = '-' . $val . '-';
                    } else {
                        $list['code'] = 1;
                        $list['msg'] = "error:选择的资产有误";
                        return $list;
                    }
                }
                $map[$k] = implode(',', $new_select_asset_id);

            }
        }

        //借用资产
        if (!empty($map['status']) && $map['status'] == 2) {
            Assets::whereIn('id', $select_asset_id)->update(['status' => 2]);
        } else {
            Assets::whereIn('id', $select_asset_id)->update(['status' => 1]);
        }

        $data_exist = Receives::where('id', $id)->first();
        if ($id && $data_exist) {
            $result = Receives::where('id', $id)->update($map);

            $list['code'] = 0;
            $list['msg'] = "修改成功";
            return $list;

        } else {
            $start = date('Y-m-d 00:00:00', time()); // 筛选当天开始时间
            $end = date('Y-m-d 23:59:59', time()); // 筛选当天结束时间
            $field = 'count(id)';

            //退库
            $sum = Receives::select($field)
                ->whereBetween('created_at', [$start, $end])
                ->count();

            $map['borrow_number'] = 'LY' . ((int) (date('Ymd', time()) . 100) + (int) (empty($sum) ? 1 : $sum + 1)); // 领用单号

            $result = Receives::create($map);
            $id = $result->id;
            $list['code'] = 0;
            $list['msg'] = "successs";
            $list['data'] = array('id' => $id);

            return $list;

        }
    }

    /**
     * 更改
     * @param $request
     * @return bool
     * @author ppjun378 <ppjun378@foxmail.com>
     */
    public static function save($request)
    {
        $id = $request->input('id', '');
        $field = $request->input('field', '');
        $value = $request->input('value', '');
        if ($field) {
            $map[$field] = $value;
            $request = Receives::where('id', $id)->update($map);
            if ($request) {
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * 删除
     * @param $request
     * @return bool\int
     * @author ppjun378 <ppjun378@foxmail.com>
     */
    public static function destory($request)
    {
        $id = $request->input('id', '');
        $res = Receives::destory($id);
        if ($res > 0) {
            return $res;
        } else {
            return false;
        }
    }

    /**
     * 恢复删除
     * @param $request
     * @return mixed
     * @author ppjun378 <ppjun378@foxmail.com>
     */
    public static function restore($request)
    {
        $id = $request->input('id', '');
        $res = Receives::where('id', $id)->restore();
        return $res;
    }

}
